package com.codedancer.campus.common.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 敏感词检测工具
 */
@Component
@Slf4j
public class SensitiveWordsDetectUtil {

    // 微信小程序appid
    @Value("${start.campus.wx.applet.appid}")
    private String wxAppletAppId;

    // 微信小程序secret
    @Value("${start.campus.wx.applet.secret}")
    private String wxAppletSecret;
    // 获取accessToken的url
    private static final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?";
    // 校验图片
    private static final String CHECK_IMAGE_URL = "https://api.weixin.qq.com/wxa/img_sec_check";
    // 校验内容
    private static final String CHECK_CONTENT_URL = "https://api.weixin.qq.com/wxa/msg_sec_check";


    /**
     * 获取微信登录token
     *
     * @return
     */
    public String getWxToken() {
        Map<String, Object> map = new HashMap<>(3);
        map.put("appid", wxAppletAppId);
        map.put("secret", wxAppletSecret);
        map.put("grant_type", "client_credential");
        String result = HttpUtil.get(GET_TOKEN_URL, map);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        return jsonObject.get("access_token").toString();
    }

    /**
     * 校验内容是否合法
     *
     * @param content
     * @return
     */
    public boolean checkContent(String content) {
        Map<String, Object> map = new HashMap<>(1);
        map.put("content", content);
        String result = HttpUtil
            .post(CHECK_CONTENT_URL + "?access_token=" + getWxToken(),
                JSONUtil.toJsonPrettyStr(map));
        JSONObject jsonObject = JSONUtil.parseObj(result);
        // 87014	内容含有违法违规内容
        int errcode = 87014;
        return jsonObject.getInt("errcode").equals(errcode);
    }
}
